/**
 * ViewPictureAction.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-12-11 17:22:48 +0800 $
 * $Revision: 1440 $
 */
package com.myspace.view.picture;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.myspace.common.exception.ApplicationException;
import com.myspace.common.util.ParamUtils;
import com.myspace.domain.Picture;
import com.myspace.domain.PictureComment;
import com.myspace.domain.User;
import com.myspace.service.picture.ViewPictureService;
import com.myspace.service.user.UserService;
import com.myspace.view.common.Constant;
import com.myspace.view.common.DispatchBaseAction;
import com.myspace.view.common.Pagination;
import com.myspace.view.common.UserUtil;

/**
 * The action to list and view picture.
 *
 * @author Allen.Chen
 *
 */
public class ViewPictureAction extends DispatchBaseAction {

	public ActionForward listPicture(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (!UserUtil.isLogin(request)) {
			return mapping.findForward("login");
		}
		ViewPictureService picService = (ViewPictureService) getWebApplicationContext()
				.getBean("viewPictureService");
		UserService userService = (UserService) getWebApplicationContext()
				.getBean("userService");

		ViewPictureForm vpForm = (ViewPictureForm) form;
		try {
			User user = this.getValidUser(request, userService);
			vpForm.setUserId(user.getId());

			// Gets picture information to list.
			// todo: modify to user
			List<List<String>> infoList = picService.getPictrueInfo(user);

			// Gets picture list by tag.
			List<String> tagList = infoList.get(1);
			String curTag = this.getCurTag(vpForm.getTag(), tagList);
			int curTagPage = ParamUtils.getIntParameter(request, "tagPage", 1);
			int totalByTag = picService.getTotalByTag(user.getId(), curTag);
			Pagination pagiTag = new Pagination(curTagPage, Constant.PAGE_SIZE,
					totalByTag);
			List<Picture> tagPicList = picService.getPicturesByTag(user,
					curTag, pagiTag.getCurPage(), pagiTag.getPageSize());

			// Add user clicks
			user.setClicks(user.getClicks() + 1);
			userService.update(user);

			vpForm.setTag(curTag);
			vpForm.setTagList(tagList);
			vpForm.setTagPicList(tagPicList);

			request.setAttribute("pagiTag", pagiTag);
			request.setAttribute("userName", user.getName());
		} catch (ApplicationException e) {
			getLogger().error(e);
			ActionMessages errors = new ActionMessages();
			errors.add(Globals.ERROR_KEY, new ActionMessage(e.getMessage(),
					false));
			this.saveErrors(request, errors);
			return mapping.findForward("error");
		}

		return mapping.findForward("success");
	}

	public ActionForward viewPictureByTag(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (!UserUtil.isLogin(request)) {
			return mapping.findForward("login");
		}
		UserService userService = (UserService) getWebApplicationContext()
				.getBean("userService");
		ViewPictureService viewPicService = (ViewPictureService) getWebApplicationContext()
				.getBean("viewPictureService");
		ViewPictureForm vpForm = (ViewPictureForm) form;
		try {
			User user = this.getValidUser(request, userService);
			List<List<String>> infoList = viewPicService.getPictrueInfo(user);

			// Gets picture list by tag.
			List<String> tagList = infoList.get(1);
			String curTag = this.getCurTag(vpForm.getTag(), tagList);
			List<Picture> picList = viewPicService.getPicturesByTag(user,
					curTag, 1, Integer.MAX_VALUE);

			// Prepares picture information to dispaly in page
			this.setPictureInfo(viewPicService, vpForm, picList);

			// Calculates prePicId and nextPicId by given picture list.
			vpForm.calculateNavPicId(picList);
			vpForm.setTag(curTag);
			vpForm.setTagList(tagList);
			vpForm.setViewType("tag");
			vpForm.setUserId(user.getId());
			request.setAttribute("userName", user.getName());
		} catch (ApplicationException e) {
			getLogger().error(e);
			ActionMessages errors = new ActionMessages();
			errors.add(Globals.ERROR_KEY, new ActionMessage(e.getMessage(),
					false));
			this.saveErrors(request, errors);
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}

	private User getValidUser(HttpServletRequest request,
			UserService userService) throws ApplicationException {
		long userId = ParamUtils.getIntParameter(request, "userId", -1);
		User user = null;
		if (UserUtil.isLogin(request)) {
			if (!StringUtils.isEmpty(request.getParameter("userId"))) {
				user = userService.getUser(userId);
				if (user == null) {
					throw new ApplicationException("该用户不存在!");
				}
			} else {
				user = UserUtil.getUser(request);
			}
		} else {
			user = userService.getUser(userId);
			if (user == null) {
				throw new ApplicationException("该用户不存在!");
			}
		}
		return user;
	}

	private void setPictureInfo(ViewPictureService viewPicService,
			ViewPictureForm vpForm, List<Picture> picList) throws Exception {
		// Gets picture by given picId.
		Picture picture = null;
		if (vpForm.getPicId() > 0) {
			picture = viewPicService.getPicture(vpForm.getPicId());
			if (picture == null) {
				throw new ApplicationException("该图像不存在");
			}
		} else if (picList != null && picList.size() > 0) {
			picture = picList.get(0);
		}

		if (picture != null) {
			List<PictureComment> commentList = viewPicService
					.getComments(picture.getId());
			vpForm.setCommentList(commentList);
			vpForm.setPicId(picture.getId());
		}

		vpForm.setPicture(picture);
	}

	private String getCurTag(String curTag, List<String> tagList)
			throws UnsupportedEncodingException {
		String ret = null;
		if (StringUtils.isEmpty(curTag)) {
			if (tagList != null && tagList.size() > 0) {
				ret = tagList.get(0);
			} else {
				ret = Constant.DEFAULT_TAG;
			}
		} else {
			boolean isFound = false;
			ret = URLDecoder.decode(curTag, Constant.ENCODING);
			for (String tag : tagList) {
				if (tag.equals(ret)) {
					isFound = true;
					break;
				}
			}
			if (isFound == false) {
				if (tagList != null && tagList.size() > 0) {
					ret = tagList.get(0);
				} else {
					ret = Constant.DEFAULT_TAG;
				}
			}
		}
		return ret;
	}

}
